package com.imut.lagain.aspect;

import com.imut.lagain.config.AsyncConfig;
import com.imut.lagain.config.PerformanceMonitorProperties;
import com.imut.lagain.service.PerformanceMonitorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 数据库性能监控切面
 * 自动记录数据库操作性能指标
 */
@Aspect
@Component
@RequiredArgsConstructor
public class DatabasePerformanceAspect {
    private static final Logger log = LoggerFactory.getLogger(DatabasePerformanceAspect.class);

    private final PerformanceMonitorService performanceMonitorService;
    private final PerformanceMonitorProperties properties;

    /**
     * 监控Mapper接口的数据库操作
     */
    @Around("execution(* com.imut.lagain.mapper.*.*(..))")
    public Object monitorDatabaseOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String operation = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        boolean success = false;
        
        try {
            Object result = joinPoint.proceed();
            success = true;
            return result;
        } catch (Exception e) {
            log.error("数据库操作异常: {}", operation, e);
            throw e;
        } finally {
            long duration = System.currentTimeMillis() - startTime;
            performanceMonitorService.recordDatabaseQuery(operation, duration, success);
            if (duration > properties.getSlowQueryThreshold()) {
                log.warn("慢查询检测: {} 耗时 {}ms", operation, duration);
            }
        }
    }

    /**
     * 监控Service层的缓存操作
     */
    @Around("execution(* com.imut.lagain.service.impl.CacheServiceImpl.*(..))")
    public Object monitorCacheOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String operation = joinPoint.getSignature().getName();
        boolean success = false;
        
        try {
            Object result = joinPoint.proceed();
            success = true;
            return result;
        } catch (Exception e) {
            log.error("缓存操作异常: {}", operation, e);
            throw e;
        } finally {
            long duration = System.currentTimeMillis() - startTime;
            performanceMonitorService.recordCacheOperation(operation, duration, success);
            if (duration > properties.getCacheSlowThreshold()) {
                log.warn("慢缓存操作检测: {} 耗时 {}ms", operation, duration);
            }
        }
    }
}